package com.dissertation.utils;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class ExcelUtil {
    // @描述：是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述：是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    /**
     * 验证EXCEL文件
     *
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            return false;
        }
        return true;
    }

    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    public static String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
    /**
     * 获取一个随机文件名
     * @param oldName
     * @return
     */
    public static String updateFileName(String oldName) {
        return UUID.randomUUID().toString() + "." + getFileExt(oldName);
    }

    public File multipartToFile(MultipartFile multfile) throws IOException {
        CommonsMultipartFile cf = (CommonsMultipartFile)multfile;
        //这个myfile是MultipartFile的
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File file = fi.getStoreLocation();
        return file;
    }

    public static Object assignValue(Object fieldType,Object value){
        if(fieldType.equals(int.class)){
            return Integer.parseInt((String) value);
        }else if(fieldType.equals(String.class)){
            return String.valueOf(value);
        }else if(fieldType.equals(Set.class)){
            String str = (String)value;
            Set<String> set = new HashSet<>(Arrays.asList(str.substring(1,str.lastIndexOf("]")).split(",")));
            return set;
        }else if(fieldType.equals(List.class)){
            String str = (String)value;
            return Arrays.asList(str.substring(1,str.lastIndexOf("]")).split(","));
        }
        return null;
    }
}